home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: 11 Apr 1996 18:35:39 -0400
- Organization: University of Maryland Baltimore County
- Message-ID: <4kk1fr$9jt@umbc9.umbc.edu>
- References: <31624BC2.70D2@sooner.net>
- NNTP-Posting-Host: umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- In article <31624BC2.70D2@sooner.net>, Eddie Bush <edwbush@sooner.net> wrote:
- |> I am trying to construct a C function that will recursively convert
- |> a string such as "1234" into it's integer equivelant (1234).
-
- Why recursively and what about the atoi() function that already exists?
-
- |> Here is what I know:
- |> 1)if you subtract the character "0" from any of the other digits "1".."9"
- |> you will get the integer value of that characer.
- |> Example: "1" - "0" is equal to 1
- |> "2" - "0" is equal to 2
- |> .
- |> .
- |> .
- |> "9" - "0" is equal to 9
-
- If you replace those strings (enclosed in "") with characters (enclosed in '')
- then I will agree with you.
-
- |> 2)the function should be called with a character pointer:
- |> Such as: convert("1234");
- |> making the prototype look something like:
- |> int convert(char *p);
-
- I'd make it 'int convert (const char *p);', but that's just my personal
- preference.
-
- |> Does anyone have an idea? This is sorta stumping me. I am aware of
- |> atoi, but I am wanting to write a recursive function that does that --
- |> for the fun of it. It's sort of a little puzzle to help me learn
- |> recursion. Any ideas?
-
- I don't see how it would be fun, but anything can be done recursively if
- you want it bad enough. Here's something to get you started that is both
- incomplete and possibly wrong altogether (aka untested):
-
- int convert (const char *p)
- {
- if (strlen (p) == 1)
- return (p[0] - '0');
- return ((int)(pow ((p[0] - '0'), (strlen (p) - 1)) + convert (&p[1])));
- }
-
- Just make sure you #include <math.h> and <string.h>. This is far from the
- most efficient solution, but at least it's recursive.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-